<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use OSS\Core\OssException;
use OSS\OssClient;

class ImageController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $image_cate_id=\request()->input('image_cate_id',1);
        $data=DB::table('image')->where('image_cate_id',$image_cate_id)->paginate(10);
        return $this->success($data);
    }

    /**
     * Store a newly created resource in storage.
     * 图片上传
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $accessKeyId = "LTAI4G2Np2fQbQ4SqfZbqXk7";
        $accessKeySecret = "eqtOSuDazSrLSPKTc0IZjMcrJfFjmE";
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = "oss-cn-hongkong.aliyuncs.com";
        // 存储空间名称
        $bucket = "brain-storm";
        // 文件名称
        $filePath = $request->file("file");

        $object = date("Y-m-d") . "/" . time() .rand(111111,999999). "." . $filePath->getClientOriginalExtension();
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object, $filePath);
            DB::table('image')->insert([
                'name'=>'https://brain-storm.oss-cn-hongkong.aliyuncs.com/'.$object,
                'img_url'=>'https://brain-storm.oss-cn-hongkong.aliyuncs.com/'.$object,
                'image_cate_id'=>$request->input('image_cate_id')
            ]);
            return $this->success(["file_path" =>'https://brain-storm.oss-cn-hongkong.aliyuncs.com/'.$object]);
        } catch (OssException $e) {
            $this->error();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $res=DB::table('image')->where('id',$id)->update($request->all());
        if($res) return $this->success();
        $this->error('更新失敗');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $res=DB::table('image')->where('id',$id)->delete();
        if($res) return $this->success();
        $this->error('刪除失敗');
    }
}
